.read()
- reading the entire content
Let's try the next example.
You need to download data0.txt, and upload it to Trinket to test the example by clicking the upward arrow button (Upload text file).
f = open("data0.txt", "r") # "r" for reading
data = f.read() # read() - read the entire content
print(data)
f.close()
# or
with open("data0.txt", "r") as f: # "r" for reading; with the 'with' keyword, file will be automatically closed.
data = f.read()
print(data)
print(f.closed)
.readline()
- reading a line
Let's try the next example.
f = open("data0.txt", "r") # "r" for reading
data = f.readline()
print(data) # is '\n' included in data?
data = f.readline()
print(data, end='')
data = f.readline()
print(data, end='')
for line in f:
- In the above example, all the 3 lines are ready.
But what if we don't know how many lines are stored in a file?
Let's try the next example.
f = open("data0.txt", "r")
for line in f:
print(line, end='')
.readlines():
- reading all the lines into a list
Let's try the next example.
f = open("data0.txt", "r")
lines = f.readlines() # the data type of lines?
print(lines)
- Let's try the next example that reads numbers from a file and computes the average.
Each line has a number, and the first line has an integer that indicates how many numbers are stored.
You need to download data1.txt, and upload it to Trinket to test the example.
f = open("data1.txt", "r")
howmany = int(f.readline())
sum = 0
for i in range(howmany):
sum = sum + int(f.readline())
average = sum / howmany
print(average)
-